package com.kanshu.ksgb.fastread.doudou.module.book.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.dl7.recycler.adapter.BaseQuickAdapter;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseListFragment;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.PageRequestParams;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.view.EmptyLayout;
import com.kanshu.ksgb.fastread.doudou.module.book.activity.SearchActivity;
import com.kanshu.ksgb.fastread.doudou.module.book.adapter.SearchResultAdapter;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo;
import com.kanshu.ksgb.fastread.doudou.common.business.event.ShelfEvent;
import com.kanshu.ksgb.fastread.doudou.module.book.retrofit.requestparams.SearchRequestParams;
import com.kanshu.ksgb.fastread.doudou.module.book.view.AdSearchResultHeaderLayout;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.presenter.BookCityPresenter;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.List;

/**
 * Created by wcy on 2017\7\17 0017.
 */

public class SearchResultFragment extends BaseListFragment<BookInfo> implements SearchActivity.CallBack {
    BookCityPresenter mPresenter = new BookCityPresenter(lifeCyclerSubject);
    AdSearchResultHeaderLayout mAdSearchResultHeaderLayout;
    String mKeyWord;
    String mExtra;

    public static SearchResultFragment newInstance() {
        SearchResultFragment fragment = new SearchResultFragment();
        return fragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPresenter.setBookView(this);
        mRequestParams = new SearchRequestParams();
        if (getActivity() instanceof SearchActivity) {
            ((SearchActivity) getActivity()).setCallBack(this);
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public void showContent(BaseResult<List<BookInfo>> result) {
        handleHeaderSearchReuslt(result);
        super.showContent(result);
    }

    private void handleHeaderSearchReuslt(BaseResult<List<BookInfo>> result) {
        String key;
        key = mKeyWord;
        if (!TextUtils.isEmpty(key)) {
            ((SearchResultAdapter) mAdapter).setKeyWord(key);
        }
        List<BookInfo> data = result.result.data;
        if (!Utils.isEmptyList(data)) {
            int pos = -1;
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).book_title.contains(mKeyWord)) {
                    pos = i;
                    break;
                }
//                if (TextUtils.equals(mKeyWord, data.get(i).book_title)) {
//                    pos = i;
//                    break;
//                }
            }
            if (pos > -1) {
                BookInfo item = data.get(pos);
                mAdSearchResultHeaderLayout.refreshByBookInfo(item);
                data.remove(pos);
            } else {
                mAdSearchResultHeaderLayout.hideOrShow(true);
            }
        }
    }

    @Override
    protected BaseQuickAdapter provideAdapter() {
        mAdapter = new SearchResultAdapter(getActivity(), mList);
        mAdSearchResultHeaderLayout = new AdSearchResultHeaderLayout(getActivity());
        mAdapter.addHeaderView(mAdSearchResultHeaderLayout);
        return mAdapter;
    }

    @Override
    protected void getContentAysnc(PageRequestParams params) {
        mPresenter.doSearch((SearchRequestParams) mRequestParams);
    }

    @Override
    public void doSearch(String s, String extra) {
        startSearch(s, extra);
    }

    private void startSearch(String s, String extra) {
        mAdSearchResultHeaderLayout.hideOrShow(true);
        mSwipeRefresh.setEnableRefresh(true);
        mKeyWord = s;
        mExtra = extra;
        mRequestParams.page = 1;
        ((SearchRequestParams) mRequestParams).book_title = mKeyWord;
        showLoading(null);
        getContentAysnc(mRequestParams);
        AdPresenter.pvuvStaticsSearch(s);
    }

    @Override
    public void clearInput() {
        if (mAdapter != null && mList != null) {
            mList.clear();
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onVagueNoData() {
        if (mEmptyLayout != null) {
            mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_NO_DATA);
        }
    }

    @Override
    public void showEmptyByCode(int code) {
        if (mAdSearchResultHeaderLayout.isShowing() && mEmptyLayout != null) {
            mEmptyLayout.hide();
            return;
        }
        super.showEmptyByCode(code);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleShelfEvent(ShelfEvent event) {
        if (mAdSearchResultHeaderLayout != null) {
            mAdSearchResultHeaderLayout.handleShelfEvent(event);
        }
        switch (event.code) {
            case ShelfEvent.ADD_TO_SHELF_SUCCESS:
                BookInfo info = (BookInfo) event.obj;
                if (info != null && !Utils.isEmptyList(mList)) {
                    for (int i = 0; i < mList.size(); i++) {
                        if (TextUtils.equals(info.book_id, mList.get(i).book_id)) {
                            mList.get(i).join_bookcase = "1";
                            mAdapter.notifyItemChanged(i + mAdapter.getHeaderViewsCount());
                            ToastUtil.showStaticMessage("加入书架成功");
                            break;
                        }
                    }
                }
                break;
            case ShelfEvent.ADD_TO_SHELF_FAIL:
                break;
            case ShelfEvent.DEL_FROM_SHELF_SUCCESS:
                List<String> ids = (List<String>) event.obj;
                if (!Utils.isEmptyList(ids) && !Utils.isEmptyList(mList)) {
                    for (String id : ids) {
                        for (int i = 0; i < mList.size(); i++) {
                            if (TextUtils.equals(id, mList.get(i).book_id)) {
                                mList.get(i).join_bookcase = "0";
                                mAdapter.notifyItemChanged(i + mAdapter.getHeaderViewsCount());
                                break;
                            }
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mAdSearchResultHeaderLayout != null) {
            mAdSearchResultHeaderLayout.recycle();
        }
        mPresenter.detachView();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(getActivity());
        MobclickAgent.onPageStart(getClass().getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(getActivity());
        MobclickAgent.onPageEnd(getClass().getSimpleName());
    }


}
